import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../../event/DataCallBack.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../routes/app_pages.dart';
import '../../../services/AudioService.dart';
import '../../../style/widget_style.dart';
import '../../../widgets/CommonWidgets.dart';
import '../../listenerTranslation/controllers/listener_translation_controller.dart';

class ListeningTransLandscapeController extends GetxController {


  double screenWidth = 0.0;
  double screenHeight = 0.0;


  final ScrollController fromController = ScrollController();

  ListenerTranslationController? listenerTranslationController;

  // 防抖计时器
  Timer? _debounceTimer;
  // 是否处于冷却状态
  bool _isCoolingDown = false;

  @override
  void onInit() {
    super.onInit();
    listenerTranslationController = Get.find<ListenerTranslationController>();

    screenWidth = MediaQuery.of(Get.context!).size.width;
    screenHeight = MediaQuery.of(Get.context!).size.height;


    WidgetsFlutterBinding.ensureInitialized();

    SchedulerBinding.instance.addPostFrameCallback((_) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeRight,
        DeviceOrientation.landscapeLeft,
      ]);
      _setFullScreen();
    });


    Future.delayed(Duration(milliseconds: 500),() {
      showPoupWindow(Get.context!);
    });
  }


  void _setFullScreen() {
    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.immersiveSticky,
      // 可选：隐藏特定系统栏（根据需求选择）
      overlays: [
        // SystemUiOverlay.top,    // 显示状态栏
        // SystemUiOverlay.bottom, // 显示导航栏
      ],
    );
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();


    // 页面退出时恢复系统UI（可选）
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values);

    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);

    _debounceTimer?.cancel(); // 组件销毁时取消计时器
  }

  void showPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => StatefulBuilder(builder: (context ,setState) {
          return SafeArea(child: Container(
            width: Get.width,
            height: 85.h,
            padding: EdgeInsets.all(15.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                InkWell(
                  onTap: () {
                    Get.back();
                    showFontPoupWindow(context);
                  },
                  child: Container(
                    padding: EdgeInsets.only(top:8.h,bottom: 8.h,left: 35.w,right: 35.w),
                    decoration: BoxDecoration(
                      boxShadow: [
                        CommonWidgets.getBoxShadow(),
                      ],
                      color:  Colors.white,
                      borderRadius: BorderRadius.circular(8), // Optional: add border radius
                    ),
                    child: Column(
                      children: [
                        Text('${listenerTranslationController!.fontDisplay.value}',style: AppStyleThemeData.normal_bold_small,),
                        Text('字体大小',style: AppStyleThemeData.normal_bold_small,)
                      ],
                    ),
                  ),
                ),
                SizedBox(width: 20.w,),
                Obx(()=>Container(
                  child: InkWell(
                    onTap: () {
                      if (_isCoolingDown) {
                        return;
                      };

                      _isCoolingDown = true;

                      if (!listenerTranslationController!.audioService.isPlaying.value) {
                        listenerTranslationController!.audioService.record();
                      } else {
                        listenerTranslationController!.audioService.pauseRecorder();
                      }

                      _debounceTimer = Timer(Duration(milliseconds: 800), () {
                        _isCoolingDown = false;
                      });

                    },
                    child: listenerTranslationController!.audioService.isPlaying.value? Image.asset('assets/images/icon_play_realtime_btn_running.png',width: 55.w,height: 55.h):
                    Image.asset('assets/images/icon_play_realtime_btn.png',width: 55.w,height: 55.h),
                  ),
                )),
                SizedBox(width: 20.w,),
                InkWell(
                  onTap: () {
                    showLanguagePoupWindow(context);
                  },
                  child: Container(
                    padding: EdgeInsets.only(top:8.h,bottom:5.h,left: 31.w,right: 31.w),
                    decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          spreadRadius: 2.w,
                          blurRadius: 7.w,
                          offset: Offset(0, 8.sp), // changes position of shadow
                        ),
                      ],
                      color:  Colors.white,
                      borderRadius: BorderRadius.circular(8), // Optional: add border radius
                    ),
                    child: Column(
                      children: [
                        Obx(()=>Text('${listenerTranslationController!.audioService.fromLanFlagDisplay.value.substring(0,1) + '-' +
                            listenerTranslationController!.audioService.toLanFlagDisplay.value.substring(0,1)}',style: AppStyleThemeData.normal_bold_small,)),
                        Text('语言设置',style: AppStyleThemeData.normal_bold_small,)
                      ],
                    ),
                  ),
                )
              ],
            ),
          ));
        }),
        backgroundColor: Colors.white.withValues(alpha: 0.5),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            top: Radius.zero, // 顶部直角
          ),
        ),
        barrierColor: Colors.black.withValues(alpha: 0.1)
    );
  }


  void showFontPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SingleChildScrollView(
          child: SafeArea(child: Container(
            padding: EdgeInsets.all(15.h),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('字体大小', style: AppStyleThemeData.HINT_TEXT_STYLE,),
                    InkWell(
                      onTap: () {
                        Get.back();
                      },
                      child: Image.asset('assets/images/icon_poup_window_close.png',width: 10.w,height: 10.h),
                    )

                  ],
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: () {
                    listenerTranslationController!.fontSize.value = 32;
                    listenerTranslationController!.fontDisplay.value = '32 (偏大)';
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('32 (偏大)',style: AppStyleThemeData.linkStyle_BIG,),
                    ],
                  ),
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: () {
                    listenerTranslationController!.fontSize.value = 24;
                    listenerTranslationController!.fontDisplay.value = '24 (大)';
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('24 (大)',style: AppStyleThemeData.linkStyle_BIG,),
                    ],
                  ),
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: () {
                    listenerTranslationController!.fontSize.value = 18;
                    listenerTranslationController!.fontDisplay.value = '18 (适中)';
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('18 (适中)',style: AppStyleThemeData.linkStyle_BIG,),
                    ],
                  ),
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: () {
                    listenerTranslationController!.fontSize.value = 16;
                    listenerTranslationController!.fontDisplay.value = '16 (小)';
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('16 (小)',style: AppStyleThemeData.linkStyle_BIG,),
                    ],
                  ),
                ),
              ],
            ),
          )),
        ),
        backgroundColor: Colors.white
    );
  }


  void showLanguagePoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          padding: EdgeInsets.only(left: 15.w,right: 15.w,top: 15.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('语言设置', style: AppStyleThemeData.HINT_TEXT_STYLE,),
                  InkWell(
                    onTap: () {
                      Get.back();
                    },
                    child: Image.asset('assets/images/icon_poup_window_close.png',width: 10.w,height: 10.h),
                  )

                ],
              ),
              SizedBox(height: 15.h,),
              CommonWidgets.getMyDivider(),
              SizedBox(height: 15.h,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  InkWell(
                    onTap: () {
                      chooseFromLanguages();
                    },
                    child: Container(
                      width: 96.w,
                      padding: EdgeInsets.all(8.w),
                      decoration: BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withValues(alpha: 0.1),
                            spreadRadius: 2.w,
                            blurRadius: 7.w,
                            offset: Offset(0, 8.sp), // changes position of shadow
                          ),
                        ],
                        color:Colors.white,
                        borderRadius: BorderRadius.circular(8), // Optional: add border radius
                      ),
                      child: Obx(()=>Text('${listenerTranslationController!.audioService.fromLanFlagDisplay.value}',style: AppStyleThemeData.normal_bold)),
                    ),
                  ),

                  Container(
                    padding: EdgeInsets.all(14.w),
                    decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          spreadRadius: 2.w,
                          blurRadius: 7.w,
                          offset: Offset(0, 8.sp), // changes position of shadow
                        ),
                      ],
                      color:Colors.white,
                      borderRadius: BorderRadius.circular(8), // Optional: add border radius
                    ),
                    child: Image.asset('assets/images/icon_index_lang_exchange.png',width: 20.w,height: 20.h,),
                  ),
                  InkWell(
                    onTap: () {
                      chooseToLanguages();
                    },
                    child: Container(
                      width: 96.w,
                      padding: EdgeInsets.all(8.w),
                      decoration: BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            spreadRadius: 2.w,
                            blurRadius: 7.w,
                            offset: Offset(0, 8.sp), // changes position of shadow
                          ),
                        ],
                        color:Colors.white,
                        borderRadius: BorderRadius.circular(8), // Optional: add border radius
                      ),
                      child: Obx(()=>Text('${listenerTranslationController!.audioService.toLanFlagDisplay.value}',style: AppStyleThemeData.normal_bold)),
                    ),
                  )
                ],
              ),
              SizedBox(height: 15.h,),
              Container(
                width: Get.width,
                child: ElevatedButton(onPressed: () {
                  changeLanguageReInitial();

                  Get.back();
                }, child: Text('确定')),
              ),
            ],
          ),
        )),
        backgroundColor: Colors.white
    );
  }

  void scrollToBottom() {
    if (fromController.hasClients) {
      Future.delayed(Duration(milliseconds: 500),() {
        fromController.animateTo(
          fromController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      });
    }
  }

  void chooseFromLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
      'code': listenerTranslationController!.audioService.fromLanguage
    });
    listenerTranslationController!.audioService.fromLanguage = languageItem['code'];
    listenerTranslationController!.audioService.fromLanFlagDisplay.value = languageItem['desc'];

  }

  void chooseToLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
      'code': listenerTranslationController!.audioService.toLanguage
    });
    listenerTranslationController!.audioService.toLanguage = languageItem['code'];
    listenerTranslationController!.audioService.toLanFlagDisplay.value = languageItem['desc'];

  }

  void changeLanguageReInitial() {
    if (listenerTranslationController!.audioService.isPlaying.value) {
      listenerTranslationController!.audioService.pauseRecorder();
    }

    listenerTranslationController!.audioService.reInitWs();
    listenerTranslationController!.audioService.connectedWsAndRecorder('wss://${NetWorkManager.WS_IP + NetWorkManager.SPEECH_RECOGNITION}?channel=azure&transStrategy=2',  DataCallBack(
        confirmCallBack: (v) {
          listenerTranslationController!.audioService.record();
        }
    ));
  }

}
